package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:wujing
 * @Date:2022/12/14 18:49
 */

/**
 * 检查用户是否已经完成登录
 */
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("登录过滤器......");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //1.放行应该直接放行的资源
        String pathes[] = {
                "/common",
                "/employee/login",//登录
                "/employee/logout",//退出登录
                "/backend",//管理员等待静态资源
                "/front"//客户等待静态资源
        };

        //获取当前用户的请求路径
        String url = req.getRequestURL().toString();
        for (String path : pathes) {
            if (url.contains(path)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }

        //2. 判断用户是否登录（session）
        HttpSession session = req.getSession();
        //注意：此处的session名称需要和表现层的session名称相同
        Object emp = session.getAttribute("emp");

        if (emp != null){

            log.info("用户已经登录，用户id为：{}",(req.getSession().getAttribute("emp")));

            Long empId = (Long) req.getSession().getAttribute("emp");
            BaseContext.setCurrentId(empId);


            //登录过了
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3. 资源不直接放行，用户未登录，访问失败，（前端）跳转到登录页面
        //手动返回R对象的json字符串给前端ajax（响应拦截器：msg=NOTLOGIN，code=0）
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }
}






























